import React from 'react';
import {Button, Icon} from 'antd';
import { isEqual, isEmpty, cloneDeep } from 'lodash';
import {WeaTools, WeaSearchGroup, WeaFormItem, WeaTable, WeaHelpfulTip} from 'ecCom';
import {WeaLocaleProvider, WeaInputLocale, WeaCheckbox} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import {  WeaPortalShare } from 'weaPortalPublic';

import SynergySetting4Designer from '../synergy/SynergySetting4Designer';
import SynergySetting4WfVersions from '../synergy/SynergySetting4WfVersions';

import Content_1_DataSource from '../Content_1_DataSource';
import Content_7_DataSource from '../Content_7_DataSource';
import Content_8_DataSource from '../Content_8_DataSource';
import Content_29_DataSource from '../Content_29_DataSource';
import Content_reportForm_DataSource from '../Content_reportForm_DataSource';
import Content_OutData_DataSource from '../Content_OutData_DataSource';
import Content_13_DataSource from '../Content_13_DataSource';
import Content_10_DataSource from '../Content_10_DataSource';
import Content_news_DataSource from '../Content_news_DataSource';
import Content_QuickEntry_DataSource from '../Content_QuickEntry_DataSource';
import Content_ecodeElement_DataSource from '../Content_ecodeElement_DataSource';
import Content_odocCenter_DataSource from '../Content_odocCenter_DataSource';
import Content_16_DataSource from '../Content_16_DataSource';
import Content_RankingList_DataSource from '../Content_RankingList_DataSource';
import Content_timeLine_DataSource from '../Content_timeLine_DataSource';

class DataSourceTable extends React.Component {
    state = {
        tabNew: this.props.tabNew,
        tabCount: this.props.tabCount,
        tabIds: this.props.tabIds,
        tabList: this.props.tabList,
        dsVisible: false,
        tabData: {},
        selectedTabIds: []
    };

    constructor(props) {
        super(props);
        this.onAddTab = this.onAddTab.bind(this);
        this.onEditTab = this.onEditTab.bind(this);
        this.onSortTab = this.onSortTab.bind(this);
        this.onDeleteTab = this.onDeleteTab.bind(this);
        this.onDeleteTabs = this.onDeleteTabs.bind(this);
        this.onOk = this.onOk.bind(this);
        this.onCancel = this.onCancel.bind(this);
        this.getSaveValues = this.getSaveValues.bind(this);
        this.guid = this.guid.bind(this);
    }

    render() {
        const {hpid, eid, ebaseid, synergyParams = {}, tabStyleList={}} = this.props;
        const {stype} = synergyParams;
        const {tabNew, tabData, tabList, dsVisible, selectedTabIds} = this.state;
        let dataSourceComponent = <div></div>;
        let columns = [{
            key: 'tabTitle',
            title: getLabel(24986, '标题'),
            dataIndex: 'tabTitle',
            width: '50%'
        }, {
            key: 'operation',
            title: getLabel(30585, '操作'),
            width: '50%',
            render: (text, record) => (
                <span>
                    <span className="portal-esetting-dst-button" onClick={() => this.onEditTab(record.tabId)}>{getLabel(30747, '设置')}</span>
                    <span className="portal-esetting-dst-button" onClick={() => this.onAddTab('saveas',record.tabId)}>{getLabel(350, '另存为')}</span>
                    {hpid < 0 && ebaseid == '8' && (stype == 'wf' || stype == 'wf_form') ? <span className="synergy-setting-btn" onClick={() => this.ss4wv.onShow({...synergyParams, hpid, ebaseid, eid, tabid: record.tabId, isGlobal: false})}>{getLabel(17632, '参数设置')}</span> : ''}
                </span>
            )
        }];
        if(ebaseid == 'quickEntry') {
            const { userid='', eShareLevel ,eid, isCustomAdd } = this.props;
            if(eShareLevel=='2' && isCustomAdd){
                columns = [{
                    key: 'tabTitle',
                    title: getLabel(24986, '标题'),
                    dataIndex: 'tabTitle',
                    width: '25%'
                }, {
                    key: 'operation',
                    title: getLabel(30585, '操作'),
                    width: '25%',
                    render: (text, record) => {
                        const { data={} } = record;
                        const { userid='' } = this.props;
                        if(data.userid == this.props.subCompanyId && eShareLevel!='2'){
                            return(
                                <span>
                            <span className="portal-esetting-dst-button" onClick={() => this.onAddTab('saveas',record.tabId)}>{getLabel(350, '另存为')}</span>
                                    {hpid < 0 && ebaseid == '8' && (stype == 'wf' || stype == 'wf_form') ? <span className="synergy-setting-btn" onClick={() => this.ss4wv.onShow({...synergyParams, hpid, ebaseid, eid, tabid: record.tabId, isGlobal: false})}>{getLabel(17632, '参数设置')}</span> : ''}
                        </span>
                            )
                        }
                        return(
                            <span>
                            <span className="portal-esetting-dst-button" onClick={() => {
                                if(userid != '1' && record.data.userid === "1"){
                                    return
                                }
                                this.onEditTab(record.tabId)
                            }}>{getLabel(30747, '设置')}</span>
                            <span className="portal-esetting-dst-button" onClick={() => this.onAddTab('saveas',record.tabId)}>{getLabel(350, '另存为')}</span>
                        </span>
                        )
                    }
                },  {
                    key: 'limit',
                    title: (
                        <React.Fragment ecId={`${this && this.props && this.props.ecId || ''}_React.Fragment@thwd9t`}>
                            <span className="portal-p4e-am-table-title">{getLabel(512999, '使用限制')}</span>
                            <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@09ip30`} style={{marginLeft:'3px'}} title={getLabel(513001, '不设置时默认为所有人')} placement="topRight" />
                        </React.Fragment>
                    ),
                    width: '25%',
                    render: (text, record) => {
                        const { data, tabTitle } = record;
                        const { shareId, isLimit } = data;
                         const title = getLabel(512999, '使用限制') + ' : ' + tabTitle;
                        return(
                                <span>
                                    <div className="portal-p4e-am-syxz" onClick={() => this.quick_share.onLoad({ content: 6, quickentry_share_uuid: shareId, eid: eid },title)}>
                                          <i style={{cursor: 'pointer', fontSize:'16px', color:'#b2b2b2'}} className="icon-coms-Flow-setting" />
                                        {isLimit && <i style={{color:'#0f9'}} className="icon-coms-Selected" />}
                                    </div>
                                </span>
                        )
                    }
                },{
                    key: 'isShow',
                    title: getLabel(26523, '显示'),
                    width: '25%',
                    render: (text, record, index) => {
                        const { data={} } = record;
                        const { userid='' } = this.props;
                        let disabled = false;
                        if(data.usertype == '1' || eShareLevel=='2'){
                            disabled = true;
                            data.isShow = '1';
                        }
                        let _datas = this.state.tabList;
                        return <div className="wea-url">
                            <div className="wea-url-toolbarmore-upload">
                                <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@n9a8sk@${index}`}
                                    value={data.isShow}
                                    disabled={disabled}
                                    onChange={(value)=>{
                                        _datas[index].data.isShow = value
                                        this.setState({
                                            tabList: _datas
                                        });
                                    }}
                                />
                            </div>
                        </div>
                    }
                }];
            } else {
                columns = [{
                    key: 'tabTitle',
                    title: getLabel(24986, '标题'),
                    dataIndex: 'tabTitle',
                    width: '50%'
                }, {
                    key: 'operation',
                    title: getLabel(30585, '操作'),
                    width: '25%',
                    render: (text, record) => {
                        const { data={} ,isme} = record;
                        const { userid='' } = this.props;
                        if(data.usertype == '3' && eShareLevel!='2' && isme != 'true'){
                            return(
                                <span>
                            <span className="portal-esetting-dst-button" onClick={() => this.onAddTab('saveas',record.tabId)}>{getLabel(350, '另存为')}</span>
                                    {hpid < 0 && ebaseid == '8' && (stype == 'wf' || stype == 'wf_form') ? <span className="synergy-setting-btn" onClick={() => this.ss4wv.onShow({...synergyParams, hpid, ebaseid, eid, tabid: record.tabId, isGlobal: false})}>{getLabel(17632, '参数设置')}</span> : ''}
                        </span>
                            )
                        }
                        return(
                                <span>
                                    <span className="portal-esetting-dst-button" onClick={() => {
                                        if(userid != '1' && record.data.userid === "1"){
                                            return
                                        }
                                        this.onEditTab(record.tabId)
                                    }}>{getLabel(30747, '设置')}</span>
                                    <span className="portal-esetting-dst-button" onClick={() => this.onAddTab('saveas',record.tabId)}>{getLabel(350, '另存为')}</span>
                                </span>
                        )
                    }
                },{
                    key: 'isShow',
                    title: getLabel(26523, '显示'),
                    width: '25%',
                    render: (text, record, index) => {
                        const { data={},isme } = record;
                        const { userid='' } = this.props;
                        let disabled = false;
                        if(data.usertype == '1' || isme == 'true'){
                            disabled = true;
                            data.isShow = '1';
                        }
                        let _datas = this.state.tabList;
                        return <div className="wea-url">
                            <div className="wea-url-toolbarmore-upload">
                                <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@fr6u29@${index}`}
                                    value={data.isShow}
                                    disabled={disabled}
                                    onChange={(value)=>{
                                        _datas[index].data.isShow = value
                                        this.setState({
                                            tabList: _datas
                                        });
                                    }}
                                />
                            </div>
                        </div>
                    }
                }];
            }

        }
        if (dsVisible) {
            const props = {
                hpid:hpid,
                eid: eid,
                tabNew: tabNew,
                tabData: tabData,
                onOk: this.onOk,
                onCancel: this.onCancel
            };
            switch (this.props.ebaseid) {
                // RSS阅读器
                case '1':
                    dataSourceComponent = <Content_1_DataSource ecId={`${this && this.props && this.props.ecId || ''}_Content_1_DataSource@dgl3ud`} {...props} />;
                    break;
                // 文档中心
                case '7':
                    dataSourceComponent = <Content_7_DataSource ecId={`${this && this.props && this.props.ecId || ''}_Content_7_DataSource@d21weh`} {...props} />;
                    break;
                // 流程中心
                case '8':
                    dataSourceComponent = <Content_8_DataSource ecId={`${this && this.props && this.props.ecId || ''}_Content_8_DataSource@oa9u0b`} {...props} />;
                    break;
                //我的协作
                case '13':
                    dataSourceComponent = <Content_13_DataSource ecId={`${this && this.props && this.props.ecId || ''}_Content_13_DataSource@ukxndh`} {...props} />;
                    break;
                // 自定义页面
                case '29':
                    dataSourceComponent = <Content_29_DataSource ecId={`${this && this.props && this.props.ecId || ''}_Content_29_DataSource@hzah1s`} {...props}/>;
                    break;
                // 图表
                case 'reportForm':
                    dataSourceComponent = <Content_reportForm_DataSource ecId={`${this && this.props && this.props.ecId || ''}_Content_reportForm_DataSource@le6zf9`} subCompanyId={this.props.subCompanyId} {...props} synergyParams={synergyParams}/>;
                    break;
                // 外部数据元素
                case 'OutData':
                    dataSourceComponent = <Content_OutData_DataSource ecId={`${this && this.props && this.props.ecId || ''}_Content_OutData_DataSource@ka1z8f`} {...props} />;
                    break;
                // 我的项目元素
                case '10':
                    dataSourceComponent = <Content_10_DataSource ecId={`${this && this.props && this.props.ecId || ''}_Content_10_DataSource@7fxcgq`} {...props} />;
                    break;
                // 公司新闻元素
                case 'news':
                    dataSourceComponent = <Content_news_DataSource ecId={`${this && this.props && this.props.ecId || ''}_Content_news_DataSource@5cmtvm`} {...props} />;
                    break;
                // 快捷方式元素
                case 'quickEntry':
                    dataSourceComponent = <Content_QuickEntry_DataSource ecId={`${this && this.props && this.props.ecId || ''}_Content_QuickEntry_DataSource@b221qg`} {...props} />;
                    break;
                // ecode自定义元素
                case 'ecodeElement':
                    dataSourceComponent = <Content_ecodeElement_DataSource ecId={`${this && this.props && this.props.ecId || ''}_Content_ecodeElement_DataSource@tijsue`} {...props} />;
                    break;
                // 公文中心元素
                case 'odocCenter':
                    dataSourceComponent = <Content_odocCenter_DataSource ecId={`${this && this.props && this.props.ecId || ''}_Content_odocCenter_DataSource@782710`} {...props} subCompanyId={this.props.subCompanyId} />;
                    break;
                //我的邮件元素
                case '16':
                    dataSourceComponent = <Content_16_DataSource ecId={`${this && this.props && this.props.ecId || ''}_Content_16_DataSource@lqv9op`} {...props} />;
                    break;
                //排行榜元素
                case 'RankingList':
                    dataSourceComponent = <Content_RankingList_DataSource ecId={`${this && this.props && this.props.ecId || ''}_Content_RankingList_DataSource@7isjnz`} {...props} />;
                    break;
                //时间轴元素
                case 'timeLine':
                    dataSourceComponent = <Content_timeLine_DataSource ecId={`${this && this.props && this.props.ecId || ''}_Content_timeLine_DataSource@lj5anp`} {...props} tabStyleList={tabStyleList} />;
                    break;
                default:
                    dataSourceComponent = <div></div>;
            }
        }

        // 记录选中的行
        const _self = this;
        const { userid='' } = this.props;
        const rowSelection = {
            onChange(selectedRowKeys) {
                _self.setState({selectedTabIds: selectedRowKeys})
            },
            getCheckboxProps (record){
                if(ebaseid == 'quickEntry') {
                    return { disabled: _self.props.eShareLevel == '1' && record.data.usertype === '3'};
                }else {
                    return false;
                }

            }
        };

        let draggable = true;
        if(ebaseid == 'quickEntry' && this.props.eShareLevel!='2') {
            draggable = false;
        }

        return (
            <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@fsh979`} title={getLabel(20885, '内容来源')} needTigger={true} showGroup={true} customComponent={
                <div>
                    {hpid < 0 && (ebaseid == '8' || ebaseid == '7') ? <span className="synergy-setting-btn" onClick={() => this.ss4d.onShow({...synergyParams, hpid, ebaseid, eid, isGlobal: true})}>{getLabel(17632, '参数设置')}</span> : ''}
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pvkjq8`} type="primary" className="portal-esetting-wsg-btn" onClick={()=>this.onAddTab('add')}>
                        <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@3nybho`} type="plus" style={{color: '#fff'}}/>
                    </Button>
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@48vqth`} type="primary" disabled={!(selectedTabIds && selectedTabIds.length)} className="portal-esetting-wsg-btn" onClick={this.onDeleteTabs}>
                        <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@jb2lp6`} type="minus" style={{color: '#fff'}}/>
                    </Button>
                    {/*<Button type="primary" onClick={() => sids.onDel()} disabled={!(selectedRowKeys && selectedRowKeys.length)}>批量删除</Button>*/}
                </div>
            }>
                {dataSourceComponent}
                <WeaPortalShare ecId={`${this && this.props && this.props.ecId || ''}_WeaPortalShare@xgcqjg`} ref={share => (this.quick_share = share)} />
                <SynergySetting4Designer ecId={`${this && this.props && this.props.ecId || ''}_SynergySetting4Designer@p7gwqm`} ref={(ss4d) => this.ss4d = ss4d}/>
                <SynergySetting4WfVersions ecId={`${this && this.props && this.props.ecId || ''}_SynergySetting4WfVersions@wo0j8e`} ref={(ss4wv) => this.ss4wv = ss4wv}/>
                <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@gleloz`} rowSelection={rowSelection} columns={columns} dataSource={tabList} pagination={false} draggable={draggable} onDrop={this.onSortTab}/>
            </WeaSearchGroup>
        );
    }

    onAddTab(type,tabId) {
        if('saveas' == type){
            let tabData = {};
            const {tabList} = this.state;
            for (let i = 0; i < tabList.length; i++) {
                if (tabList[i].tabId == tabId) {
                    tabData =cloneDeep( tabList[i].data);
                    break;
                }
            }
            tabData.id = '';
            if(this.props.ebaseid == 'quickEntry') {
                tabData.isLimit = false;
            }
            this.setState({
                tabData: tabData,
                dsVisible: true
            });
        }else{
            this.setState({
                tabData: {},
                dsVisible: true
            });
        }

    }

    onDeleteTabs() {
        const {selectedTabIds} = this.state;
        for (let i = 0, len = selectedTabIds.length; i < len; i++) {
            this.onDeleteTab(selectedTabIds[i]);
        }
        this.setState({selectedTabIds: []});
    }

    onDeleteTab(tabId) {
        const {tabList} = this.state;
        for (let i = 0, len = tabList.length; i < len; i++) {
            if (tabList[i].tabId == tabId) {
                tabList.splice(i, 1);
                break;
            }
        }
        this.setState({tabList: tabList});
    }

    onEditTab(tabId) {
        let tabData = {};
        const {tabList} = this.state;
        for (let i = 0, len = tabList.length; i < len; i++) {
            if (tabList[i].tabId == tabId) {
                tabData = tabList[i].data;
                break;
            }
        }

        this.setState({
            tabData: tabData,
            dsVisible: true
        });
    }

    guid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0,
                v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }


    onOk(values) {
        let tabList = this.state.tabList;
        let tabCount = this.state.tabCount || 0;
        let id = values.id;
        // 根据id是否存在判断是新增还是编辑
        if (!!id) { // 编辑保存
            if(this.props.ebaseid == 'quickEntry') {
                for (let i = 0, len = tabList.length; i < len; i++) {
                    if (tabList[i].tabId == id) {
                        tabList[i].tabTitle = WeaInputLocale.getCurrentLabel(values.title);
                        tabList[i].isme = 'true';
                        tabList[i].data = values;
                    }
                }
            }else{
                for (let i = 0, len = tabList.length; i < len; i++) {
                    if (tabList[i].tabId == id) {
                        tabList[i].tabTitle = WeaInputLocale.getCurrentLabel(values.title);
                        tabList[i].data = values;
                    }
                }
            }
        } else { // 新建保存
            id = String(++tabCount);
            values.id = id;
            if(this.props.ebaseid == 'quickEntry') {
				id = this.guid();
                values.id = id;
                values.shareId = this.guid();
                tabList.push({
                    key: id,
                    tabId: id,
                    isme:'true',
                    tabTitle: WeaInputLocale.getCurrentLabel(values.title),
                    data: values
                });
            }else {
                tabList.push({
                    key: id,
                    tabId: id,
                    tabTitle: WeaInputLocale.getCurrentLabel(values.title),
                    data: values
                });
            }

        }
        this.setState({
            tabCount: tabCount,
            tabList: tabList,
            dsVisible: false
        });
    }

    onCancel() {
        this.setState({
            dsVisible: false
        });
    }

    onSortTab(tabList) {
        let tabListNew = tabList;
        if(this.props.ebaseid == 'quickEntry') {
            tabListNew = tabListNew.map((item, index) => {
                item.orderNum = index;
                item.data.orderNum = index;
                return item;
            })
        }
        this.setState({
            tabList: tabListNew
        });
    }

    getSaveValues() {
        return {
            tabIds: this.state.tabIds,
            tabList: this.state.tabList
        };
    }
}

export default DataSourceTable;
